import json
import os
from datetime import datetime
from models import User, Admin, Book, BorrowRecord

class Database:
    def __init__(self):
        self.users = {}
        self.books = {}
        self.borrow_records = []
        self.load_data()
        
        # 如果没有管理员账户，创建一个默认管理员
        if not any(isinstance(user, Admin) for user in self.users.values()):
            admin = Admin("admin", "admin123")
            self.users[admin.username] = admin
            self.save_data()

    def load_data(self):
        if os.path.exists('library_data.json'):
            with open('library_data.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
                
                # 加载用户数据
                for username, user_data in data.get('users', {}).items():
                    if user_data.get('is_admin'):
                        self.users[username] = Admin(username, user_data['password'])
                    else:
                        self.users[username] = User(username, user_data['password'])
                
                # 加载图书数据
                for isbn, book_data in data.get('books', {}).items():
                    book = Book(
                        book_data['title'],
                        book_data['author'],
                        isbn,
                        book_data['quantity']
                    )
                    self.books[isbn] = book
                
                # 加载借阅记录
                for record_data in data.get('borrow_records', []):
                    book = self.books.get(record_data['book_isbn'])
                    user = self.users.get(record_data['username'])
                    if book and user:
                        record = BorrowRecord(book, user)
                        record.borrow_time = datetime.fromisoformat(record_data['borrow_time'])
                        if record_data.get('return_time'):
                            record.return_time = datetime.fromisoformat(record_data['return_time'])
                        self.borrow_records.append(record)
                        book.borrow_records.append(record)
                        user.borrowed_books.append(book)

    def save_data(self):
        data = {
            'users': {
                username: {
                    'password': user.password,
                    'is_admin': isinstance(user, Admin)
                }
                for username, user in self.users.items()
            },
            'books': {
                isbn: {
                    'title': book.title,
                    'author': book.author,
                    'quantity': book.quantity
                }
                for isbn, book in self.books.items()
            },
            'borrow_records': [
                {
                    'book_isbn': record.book.isbn,
                    'username': record.user.username,
                    'borrow_time': record.borrow_time.isoformat(),
                    'return_time': record.return_time.isoformat() if record.return_time else None
                }
                for record in self.borrow_records
            ]
        }
        
        with open('library_data.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def authenticate_user(self, username, password):
        user = self.users.get(username)
        if user and user.password == password:
            return user
        return None

    def add_user(self, user):
        self.users[user.username] = user
        self.save_data()

    def delete_user(self, username):
        if username in self.users:
            del self.users[username]
            self.save_data()
            return True
        return False

    def get_all_users(self):
        return list(self.users.values())

    def add_book(self, book):
        self.books[book.isbn] = book
        self.save_data()

    def delete_book(self, isbn):
        if isbn in self.books:
            del self.books[isbn]
            self.save_data()
            return True
        return False

    def get_book(self, isbn):
        return self.books.get(isbn)

    def update_book(self, book):
        self.books[book.isbn] = book
        self.save_data()

    def get_all_books(self):
        return list(self.books.values())

    def search_books(self, keyword):
        keyword = keyword.lower()
        return [
            book for book in self.books.values()
            if keyword in book.title.lower() or
               keyword in book.author.lower() or
               keyword in book.isbn.lower()
        ]

    def borrow_book(self, user, isbn):
        book = self.books.get(isbn)
        if not book or book.quantity <= 0:
            return False
        
        # 检查用户是否已经借阅了这本书
        if book in user.borrowed_books:
            return False
        
        book.quantity -= 1
        record = BorrowRecord(book, user)
        self.borrow_records.append(record)
        book.borrow_records.append(record)
        user.borrowed_books.append(book)
        self.save_data()
        return True

    def return_book(self, user, isbn):
        book = self.books.get(isbn)
        if not book or book not in user.borrowed_books:
            return False
        
        # 找到对应的借阅记录
        for record in book.borrow_records:
            if record.user == user and not record.return_time:
                record.return_time = datetime.now()
                book.quantity += 1
                user.borrowed_books.remove(book)
                self.save_data()
                return True
        return False

    def get_borrow_history(self, user):
        return [
            {
                'book': record.book,
                'borrow_time': record.borrow_time,
                'return_time': record.return_time
            }
            for record in self.borrow_records
            if record.user == user
        ] 